package com.wallet.provider.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wallet.common.vo.PageResult;
import com.wallet.provider.mapper.MenuMapper;
import com.wallet.provider.model.Menu;
import com.wallet.provider.model.vo.TreeNodeVo;
import com.wallet.provider.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public PageResult<Menu> getMenuList(int pageNum, int pageSize, String order, String ordername) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Menu> menus = menuMapper.selectByPageNumSize(pageNum, pageSize, order, ordername);
        return PageResult.getPageResult(menus);
    }

    @Override
    public List<TreeNodeVo> getMenuTree() {
        return menuMapper.selectMenuTree();
    }

    @Override
    public List<TreeNodeVo> getMenuTree(Long roleId) {
        // 查询所有操作
        List<TreeNodeVo> treeNodeVoList =  menuMapper.selectMenuTree();
        // 查询指定角色所拥有的操作
        List<Menu> menuList =  menuMapper.selectMenuRoleId(roleId);
        Map<Long, Menu> menuMap = new HashMap<>();
        // 处理选择中
        this.handlerTreeNodeSelectable(treeNodeVoList, menuMap);
        return  treeNodeVoList;


    }

    @Override
    public Menu getMenuById(Long id) {
        return menuMapper.selectByPrimaryKey(id);
    }



    private void  handlerTreeNodeSelectable(List<TreeNodeVo> treeNodeVoList,  Map<Long, Menu> menuMap){
        for (TreeNodeVo treeNodeVo: treeNodeVoList){
            treeNodeVo.setSelectable(menuMap.get(treeNodeVo) != null);
            List<TreeNodeVo> subTreeNodes = treeNodeVo.getNodes();
            if (!CollectionUtils.isEmpty(subTreeNodes)){
                handlerTreeNodeSelectable(subTreeNodes, menuMap);
            }else{
                return ;
            }
        }
    }
    @Override
    public boolean updateMenu(Menu menu) {
        Date now = new Date();
        menu.setUpdateTime(now);
        return menuMapper.updateByPrimaryKeySelective(menu) > 0;
    }

    @Override
    public Boolean deleteMenu(Long[] ids) {
        return menuMapper.deleteByIds(ids) > 0;
    }
}
